import 'dart:convert';

import 'package:elephant_fish/TRTCChatSalonDemo/ui/room/VoiceRoomPage.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/model/TRTCLiveRoom.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/model/TRTCLiveRoomDef.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/list/LiveRoomCreate.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/list/LiveRoomList.dart';
import 'package:elephant_fish/dao/login_dao.dart';
import 'package:elephant_fish/debug/GenerateTestUserSig.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/rank_list_request.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/i10n/localization_intl.dart';
import 'package:elephant_fish/model/user.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/page/index_home_page.dart';
import 'package:elephant_fish/page/index_live_broadcast_page.dart';
import 'package:elephant_fish/page/index_my_info_page.dart';
import 'package:elephant_fish/page/index_shop_page.dart';
import 'package:elephant_fish/page/login_page.dart';
import 'package:elephant_fish/page/message_page.dart';
import 'package:elephant_fish/page/perfect_information_page.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  DateTime lastPopTime;

  UserInfoEntity _userInfoEntity;
  TRTCLiveRoom trtcLiveRoomServer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUserInfo();
    getRankList();
  }

  getRankList() async {
    BaseRequest request;
    request = RankListRequest(0);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    request.addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    print(result);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: DefaultTabController(
        length: 5,
        child: Scaffold(
            floatingActionButtonLocation:
                FloatingActionButtonLocation.centerDocked,
            floatingActionButton: FloatingActionButton(
              foregroundColor: Color(0xff),
              backgroundColor: Color(0xff140c3c),
              child: Icon(
                Icons.circle,
                size: 50,
                color: Color(0xffff215d),
              ),
              onPressed: () {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) => LiveRoomCreatePage(
                          arguments: {'userInfo': _userInfoEntity},
                        )));
              },
            ),
            bottomNavigationBar: buildBottomNavigation(),
            body: IndexedStack(
              sizing: StackFit.expand,
              index: currentIndex,
              children: bodyWidgetList,
            )),
      ),
      onWillPop: () {
        exit();
      },
    );
  }

  ///选中的标签
  int currentIndex = 0;

  ///图标区
  List<String> normalIcon = [
    "assets/images/home.png",
    "assets/images/shop.png",
    "assets/images/message.png",
    "assets/images/my.png",
    "assets/images/home_checked.png",
    "assets/images/shop_checked.png",
    "assets/images/message_checked.png",
    "assets/images/my_checked.png",
  ];

  List<String> normalTitle = ["首页", "商城", "消息", "我的"];

  List<Widget> bodyWidgetList = [
    IndexHomePage(),
    IndexShopPage(),
    MessagePage(),
    IndexMyInfoPage(
      user: User(
          1,
          '六月的雨',
          'https://img0.baidu.com/it/u=3577691567,3678877448&fm=26&fmt=auto&gp=0.jpg',
          123,
          486,
          'wgaudhuwakh123123213213123dukwahd12312321312321321321ukhadukhwauk'),
    )
  ];

  BottomAppBar buildBottomNavigation() {
    double itemWidth = MediaQuery.of(context).size.width / 5;
    return BottomAppBar(
      color: Color(0xff140c3c),
      // shape: CircularNotchedRectangle(),
      child: Row(
        children: [
          SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(0)),
          SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(1)),
          SizedBox(height: 49, width: itemWidth),
          SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(2)),
          SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(3))
        ],
      ),
    );
  }

  Widget bottomAppBarItem(int index) {
    //设置默认未选中的状态
    TextStyle style = TextStyle(fontSize: 10, color: Color(0xfff3f3f3));
    // String imgUrl = normalImgUrls[index];
    String imgUrl = normalIcon[index];
    if (currentIndex == index) {
      //选中的话
      style = TextStyle(fontSize: 10, color: Color(0xfff3f3f3));
      // imgUrl = selectedImgUrls[index];
      imgUrl = normalIcon[index + 4];
    }
    //构造返回的Widget
    Widget item = Container(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset(
              imgUrl,
              width: 32,
            ),
            // normalIcon[index],
            Text(
              normalTitle[index],
              style: style,
            ),
          ],
        ),
        onTap: () {
          if (currentIndex != index) {
            setState(() {
              currentIndex = index;
              print(index);
            });
          }
        },
      ),
    );
    return item;
  }

  Future<void> getUserInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserInfoRequest();
    request.add('type', 2).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
    setState(() {
      _userInfoEntity = UserInfoEntity.fromJson(
          new Map<String, dynamic>.from(result['data']));
    });
    login();
  }

  Future<void> login() async {
    String loginId = _userInfoEntity.userId;
    if ((await Permission.camera.request().isGranted &&
        await Permission.microphone.request().isGranted)) {
    } else {
      TxUtils.showErrorToast('需要获取音视频权限才能进入', context);
      return;
    }
    if (userId == '') {
      TxUtils.showErrorToast(Languages.of(context).errorUserIDInput, context);
      return;
    }
    if (double.tryParse(userId) == null) {
      TxUtils.showErrorToast(Languages.of(context).errorUserIDNumber, context);
      return;
    }
    await trtcLiveRoomServer.login(
        GenerateTestUserSig.sdkAppId,
        loginId,
        await GenerateTestUserSig.genTestSig(loginId),
        TRTCLiveRoomConfig(useCDNFirst: false));
    await trtcVoiceRoom.login(
      GenerateTestUserSig.sdkAppId,
      loginId,
      GenerateTestUserSig.genTestSig(loginId),
    );
  }

  Future<void> exit() async {
    if (lastPopTime == null ||
        DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
      lastPopTime = DateTime.now();
      TxUtils.showToast('再按一次退出', context);
    } else {
      lastPopTime = DateTime.now();
      // 退出app
      await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }
  }
}
